package com.lagou.utils;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ZkUtils {

    private static ZooKeeper zooKeeper;


    public static void connectZookeeper(String zookeeperAddress, int sessionTimeout, Watcher watcher) throws IOException {
        zooKeeper = new ZooKeeper(zookeeperAddress, sessionTimeout, watcher);
    }


    public static void setNoteData(String nodeName, String data) throws KeeperException, InterruptedException {
        zooKeeper.setData("/" + nodeName, data.getBytes(), -1);
    }


    public static String getNoteData(String nodeName) throws KeeperException, InterruptedException {
        byte[] data = zooKeeper.getData("/" + nodeName, false, null);
//        System.out.println("data:" + new String(data));
        return new String(data, StandardCharsets.UTF_8);

    }

    public void createNoteSync(String namespace,String ip,String port) throws KeeperException, InterruptedException {
        // 创建节点
        String path = "/" + namespace + ip + ":" + port;
//        String content = IP + ":" + PORT;
        zooKeeper.setData(path, String.valueOf(System.currentTimeMillis()).getBytes(), -1);
    }
}
